package com.xinyue.auto.reader.process;

import org.dom4j.Element;

import com.xinyue.auto.annotation.SetNull;
import com.xinyue.auto.bean.Page;
import com.xinyue.auto.exception.PageException;
import com.xinyue.auto.reader.Process;
import com.xinyue.auto.reader.ProcessContext;
import com.xinyue.auto.reader.util.PageUtil;
import com.xinyue.auto.util.StringUtil;

public class PageProcess extends ProcessContext{
	public PageProcess(Process read) {
		super(read);
	}

	@SetNull
	private Page page;//页面数据封装对象
	
	@Override
	protected void validate() throws Exception {
		Element ep = xml.element(page_);
		
		if(ep != null) {
			try {
				String fold = ep.attributeValue(folder_);
				if(StringUtil.isNull(fold)) {
					throw new Exception("folder属性未定义或其值为空");
				}
				//判断是否有子标签
				if(ep.elements().size() == 0) {
					throw new Exception("未定义子标签");
				}
				
				//创建page对象并读取数据
				page = new Page();
				page.setPagePath(fold);
				
				//index
				Element index = ep.element(index_);
				if(index != null) {
					String temp = index.attributeValue(template_);
					if(StringUtil.isNull(temp)) {
						throw new Exception("index标签未定义template属性或其值为空");
					}
					//验证模版是否合法
					temp = PageUtil.validate(temp);
					//验证页面文件名称
					String name = index.attributeValue(name_);
					if(StringUtil.isNull(name)) {
						name = "index";
					}
					
					page.setIndexName(name);
					page.setIndex(true);
					page.setIndexTemp(temp);
				}
				
				//build
				Element build = ep.element(build_);
				if(build != null) {
					String temp = build.attributeValue(template_);
					if(StringUtil.isNull(temp)) {
						throw new Exception("build标签未定义template属性或其值为空");
					}
					//验证模版是否合法
					temp = PageUtil.validate(temp);
					//验证页面文件名称
					String name = build.attributeValue(name_);
					if(StringUtil.isNull(name)) {
						name = "build";
					}
					
					page.setBuildName(name);
					page.setBuild(true);
					page.setBuildTemp(temp);
				}
				
				//look
				Element look = ep.element(look_);
				if(look != null) {
					String temp = look.attributeValue(template_);
					if(StringUtil.isNull(temp)) {
						throw new Exception("look标签未定义template属性或其值为空");
					}
					//验证模版是否合法
					temp = PageUtil.validate(temp);
					//验证页面文件名称
					String name = look.attributeValue(name_);
					if(StringUtil.isNull(name)) {
						name = "look";
					}
					
					page.setLookName(name);
					page.setLook(true);
					page.setLookTemp(temp);
				}
			} catch (Exception e) {
				throw new PageException(e.getMessage(), holder.getException());
			}
		}
	}

	@Override
	protected void install() {
		holder.getEntity().setPage(page);
	}
}